package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.domain.dto.BarChartDto;
import com.ruoyi.system.mapper.SysStudentMapper;
import com.ruoyi.system.service.ISysStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.List;

/**
 * ClassName: ISysStudentServiceImpl
 * Package: com.ruoyi.system.service.impl
 * Description: 学生信息service层业务处理
 *
 * @Author: blw
 * @Create: 2023/11/16 - 14:12
 * @Version: v1.0
 */
@Service
public class SysStudentServiceImpl extends ServiceImpl<SysStudentMapper, SysStudent> implements ISysStudentService {
    /**
     * 导入学生数据
     *
     * @param studentList     学生信息列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则更新数据
     * @param operName        操作用户
     * @return 结果
     */

    private static final Logger log = LoggerFactory.getLogger(SysStudentServiceImpl.class);

    @Autowired
    private SysStudentMapper studentMapper;

    @Autowired
    protected Validator validator;

    @Override
    public String importStudent(List<SysStudent> studentList, boolean isUpdateSupport, String operName) {
        log.info("学生数据总条数:{}",studentList.size());
        if(StringUtils.isNull(studentList)||studentList.size()==0){
            throw new ServiceException("导入数据不能为空");
        }
        int successNum = 0;
        int failedNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failedMsg = new StringBuilder();

        for (SysStudent student:studentList)
        {
            try
            {
                //验证是否存在这个学生 以name为key吧
                QueryWrapper<SysStudent> queryWrapper = Wrappers.query();
                queryWrapper.eq("student_name",student.getStudentName())
                            .eq("student_status",0)
                            .last("limit 1");
                SysStudent s = this.getOne(queryWrapper);
                if (StringUtils.isNull(s)){
                    BeanValidators.validateWithException(validator,student);
                    studentMapper.insert(student);
                    log.info("新增成功,操作用户是：{}",operName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getStudentName() + " 导入成功");
                }
                else if (isUpdateSupport){
                   BeanValidators.validateWithException(validator,student);
                   studentMapper.update(student,null);
                    log.info("更新成功,操作用户是:{}",operName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getStudentName() + " 更新成功");
                }else{
                    failedNum++;
                    failedMsg.append("<br/>" + failedNum + "、账号 " + student.getStudentName() + " 已存在");
                }

            }catch (Exception e)
            {
               failedNum++;
                String msg = "<br/>" + failedNum + "、学生 " + student.getStudentName() + " 导入失败：";
                failedMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failedNum > 0){
            failedMsg.insert(0,"很抱歉，导入失败！共 " + failedNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failedMsg.toString());
        }else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询柱状图所需数据
     *
     * @return 返回的聚合图表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<BarChartDto> queryBarChartList() {

         return  studentMapper.queryBarChartList();
    }

    /**
     * 查询学生信息列表
     *
     * @param sysStudent 学生信息
     * @return 学生信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysStudent> queryList(SysStudent sysStudent) {
        QueryWrapper<SysStudent> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(sysStudent.getStudentName())){
            queryWrapper.eq("student_name",sysStudent.getStudentName());
        }
        if (StringUtils.isNotNull(sysStudent.getStudentAge())){
            queryWrapper.eq("student_age",sysStudent.getStudentAge());
        }
        if (StringUtils.isNotEmpty(sysStudent.getStudentHobby())){
            queryWrapper.eq("student_hobby",sysStudent.getStudentHobby());
        }
        return this.list(queryWrapper);
    }
}
